package net.begincode.common.upload;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class QiNiuUploader implements FileUploader {
    private static Logger LOGGER = LoggerFactory.getLogger(QiNiuUploader.class);

    private UploadManager uploadManager;
    private String token;

    public QiNiuUploader(String accessKey, String secretKey, String bucketName) {
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        //密钥配置
        Auth auth = Auth.create(accessKey, secretKey);
        token = auth.uploadToken(bucketName);
        uploadManager = new UploadManager(c);
    }

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private String getUpToken() {
        return token;
    }


    public String fileUpload(String fileName, String filePath) {
        try {
            //调用put方法上传
            Response res = uploadManager.put(filePath, fileName, getUpToken());
            //打印返回的信息
            return fileName;
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            LOGGER.error("文件上传异常", e);
            return "";
        }
    }

    public String fileUpload(File file) {
        return fileUpload(file.getName(), file.getAbsolutePath());
    }
}
